package com.core.family.gen.config;

import com.core.common.exception.BDException;
import com.core.family.gen.cons.DSTypeEnum;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Objects;

/**
 * @description:
 * @author: honglei
 * @time: 2021/3/23 0023 16:55
 */
@Component
@Data
public class GenConfManger {

    @Resource
    GenProperties properties;

    private GenProperties.BaseProperties baseConf;


    private GenProperties.DatasourceProperties getDS() {

        if (Objects.nonNull(properties)) {
            if (!CollectionUtils.isEmpty(properties.getDs()) && properties.getDs().containsKey(properties.getActive())) {
                return properties.getDs().get(properties.getActive());
            }
        }
        throw new BDException("数据源不存在");
    }

    public String getUserName() {
        return getDS().getUserName();
    }

    public String getPasswd() {
        return getDS().getPassword();
    }

    public String getUrl() {
        return getDS().getUrl();
    }

    public String getDriver() {
        return getDS().getDriverClassName();
    }

    public void setActive(String active) {
        if (!properties.getDs().containsKey(active)) {
            throw new BDException("数据源不存在");
        }
        properties.setActive(active);
    }

    public void addDs(String key, GenProperties.DatasourceProperties ds, boolean active) {
        properties.getDs().put(key, ds);
        if (active) {
            properties.setActive(key);
        }
    }

    /**
     * 获取包路径
     *
     * @return
     */
    public String getPackagePath() {
        return baseConf.getPackageName().replace(".", "\\");
    }


    public DSTypeEnum getDsType() {
        String driver = getDS().getDriverClassName();
        for (DSTypeEnum e : DSTypeEnum.values()) {
            if (driver.contains(e.getName())) {
                return e;
            }
        }
        throw new BDException("数据库类型不支持");
    }

    @PostConstruct
    public void initBaseConf() {
        if (Objects.isNull(baseConf)) {
            baseConf = new GenProperties.BaseProperties();
        }
        if (Objects.nonNull(properties.getGenCof())) {
            BeanUtils.copyProperties(properties.getGenCof(), baseConf);
        }

    }
}
